﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.IO;
using System.Data.OracleClient;
using System.Drawing;
using Business.Common;
using WF_Business;

/// <summary>
/// 添加web页面的后台
/// </summary>
public partial class ManageInside_WebPubManager : PageBase
{
    string type = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        labMsg.Text = Request.QueryString["type"];
        if (!IsPostBack)
        {
            if (Request["action"] == "modify")
            {
                string sql = "select * from xt_other where id='{0}'";
                sql = string.Format(sql, Request["id"]);
                DataTable dt = null;
                SysParams.OAConnection().RunSql(sql, out dt);
                if (dt.Rows.Count > 0)
                {
                    this.txt_title.Text = dt.Rows[0]["title"].ToString();
                    this.FreeTextBox1.Text = dt.Rows[0]["CONTENT"].ToString();
                }
            }
        }
    }

    /// <summary>
    /// 提交数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        UpdateData();
        Response.Redirect("More.aspx?type=" + Request.QueryString["type"]);
    }

    /// <summary>
    /// 更新数据
    /// </summary>
    private void UpdateData()
    {
        try
        {
            string strSql = string.Empty;
            string sID = string.Empty;
            string imgurl = "";
            string smallImgUrl = "";
            string title = this.txt_title.Text;
            string content = FreeTextBox1.Text;
            if (content != "")
            {
                if (content.IndexOf("images/images/") > 0)
                {
                    int i = content.IndexOf("images/images/");
                    string str = content.Substring(i);
                    int j = str.IndexOf('"');
                    imgurl = str.Substring(0, j);
                    string path = Server.MapPath("../") + imgurl;
                    //string newpath = Server.MapPath("../") + imgurl.Replace("images/images/", "images/img/");
                    string type = imgurl.Substring(imgurl.LastIndexOf("."));
                    string filename = Guid.NewGuid().ToString() + type;
                    string newpath = Server.MapPath("../") + "images/img/" + filename;
                    HandleImages(path, newpath);
                    smallImgUrl = "images/img/" + filename;
                }
            }

            if (Request["action"] == "modify")
            {
                sID = Request["id"];
            }
            else
            {
                sID = System.Guid.NewGuid().ToString().Replace("-", "");
            }
            string iNotice = ckbNotice.Checked == true ? "1" : "0";

            if (Request["action"] == "modify")
            {
                strSql = string.Format(@"update xt_other set CONTENT=:conParam,title='{0}' where 
                            id='{1}'", txt_title.Text, Request["id"]);

                string id = Request["id"];
                System.Data.IDataParameter[] idp = new System.Data.OracleClient.OracleParameter[1];
                idp[0] = new OracleParameter(":conParam", OracleType.Clob);
                idp[0].Value = FreeTextBox1.Text;
                SysParams.OAConnection().RunSql(strSql, ref idp);
            }
            else//不是修改就添加
            {
                strSql = string.Format(@"insert into xt_other(TITLE,CONTENT,TYPE,IS_NOTICE,id,userid,show_no) 
                    VALUES ('{0}',:conParam,'{1}','{2}','{3}','{4}',(select max(nvl(show_no,0))+1 from xt_other where type='{1}'))", txt_title.Text,
                    Request.QueryString["type"], iNotice, sID, UserId);

                System.Data.IDataParameter[] idp = new System.Data.OracleClient.OracleParameter[1];
                idp[0] = new OracleParameter(":conParam", OracleType.Clob);
                idp[0].Value = FreeTextBox1.Text;
                SysParams.OAConnection().RunSql(strSql, ref idp);

                //上传附件
                upload(sID);

                //设定所有人员
                Notice notice = new Notice();
                notice.InsertNoticeUser(sID);
            }
            alertMessage("操作成功！");

            //清空数据
            this.txt_title.Text = "";
            this.FreeTextBox1.Text = "";
        }
        catch (Exception ex)
        {
            alertMessage(ex.Message);
        }
    }

    /// <summary>
    /// 调用前台javascript弹出信息并跳转页面
    /// </summary>
    /// <param name="mess">信息内容</param>
    /// <param name="url">跳转页面</param>
    protected void alertMessage(string mess)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "url", "alert('" + mess + "');", true);
    }

    /// <summary>
    /// 上传附件
    /// </summary>
    /// <param name="Aid"></param>
    private void upload(string Aid)
    {
        for (int i = 0; i < Request.Files.Count; i++)
        {
            if (Request.Files[i].ContentLength > 0)
            {
                bool IsFileExist;
                string FileName = PathToName(Request.Files[i].FileName);
                IsFileExist = IsFileUploaded(FileName);  //检查在XT_UPLOADFILE表中，当前用户是否上传过该文件。以文件名和用户ID组合为准
                string path = Server.MapPath(".") + "\\UpLoadFile\\";
                if (!IsFileExist)
                {
                    Request.Files[i].SaveAs(path + FileName);
                    insertFilere(FileName, Aid);
                }
            }
        }
    }

    /// <summary>
    /// 插入附件关联信息
    /// </summary>
    /// <param name="filename"></param>
    /// <param name="articleid"></param>
    public void insertFilere(string filename, string articleid)
    {
        string sql = "insert into xt_uploadfile(filename,flag,archivesno,OWNER) values ('{0}','2','{1}','2')";

        string strCurrentPath = Request.Url.ToString().ToLower();
        string strFilePath = string.Format("{0}UpLoadFile/{1}", strCurrentPath.Substring(0,strCurrentPath.LastIndexOf("/")+1), filename);
        sql = string.Format(sql, strFilePath, articleid, UserId);
        SysParams.OAConnection().RunSql(sql);
    }

    //取文件名
    public string PathToName(string path)
    {
        int pos = path.LastIndexOf("\\");
        return path.Substring(pos + 1);
    }

    #region  判断文件是否上传
    //判断文件是否上传
    private bool IsFileUploaded(String filename)
    {
        String sql1 = null;

        sql1 = string.Format("select count(*) from xt_uploadfile where filename='{0}' and owner = '{1}' and flag='1'",
            filename, UserId);

        int mycount = Convert.ToInt32(SysParams.OAConnection().GetValue(sql1));

        if (mycount > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// 处理图片
    /// </summary>
    /// <param name="imagepath">处理前的Image路径</param>
    /// <param name="size">图片的长宽</param>
    /// <param name="saveUrl">处理后的Image路径</param>
    public void HandleImages(string imagepath, string saveUrl)
    {
        //width: 246px; height: 180px
        Size size = new Size(246, 180);

        System.Drawing.Image i = System.Drawing.Image.FromFile(imagepath);

        Bitmap outter = new Bitmap(i, SetSize(i));

        FileStream f = new FileStream(saveUrl, FileMode.CreateNew);


        outter.Save(f, System.Drawing.Imaging.ImageFormat.Jpeg);

        outter.Dispose();
        f.Close();
        f.Dispose();
    }

    public Size SetSize(System.Drawing.Image img)
    {
        double with = Convert.ToDouble(img.Width);
        double hight = Convert.ToDouble(img.Height);
        int newWith = 0;
        int newHight = 0;
        double ft = 0;
        if (with > hight)
        {
            ft = 180 / with;
            newWith = 246;
            newHight = Convert.ToInt32(ft * hight);
        }

        if (with < hight)
        {
            ft = 246 / hight;
            newHight = 180;
            newWith = Convert.ToInt32(ft * with);
        }
        else
        {
            newHight = 180;
            newWith = 246;
        }
        Size size = new Size(newWith, newHight);
        return size;
    }
    #endregion
}
